package com.xkdx.caipiao.application;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.ActivityManager;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.MKGeneralListener;
import com.baidu.mapapi.map.MKEvent;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.xkdx.caipiao.MainTabActivity;
import com.xkdx.caipiao.R;
import com.xkdx.caipiao.module.cache.XkCache;
import com.xkdx.caipiao.statics.IConstants;
import com.xkdx.caipiao.util.SharePrefenceUtil;

public class MyApplication extends Application {
	public static ImageLoader imageLoader = ImageLoader.getInstance();
	private static MyApplication mInstance = null;
	public static boolean m_bKeyRight = true;
	public BMapManager mBMapManager = null;
	public static final String strKey = "vSwmt16FVw5usIfNud8aYGNG";
	public static LocationClient mLocClient;
	public static MyLocationListenner myLocationListenner;
	private static Application mApp = null;
	private SharePrefenceUtil sp;
	private int count = 0;
	public static int redpackageNum;
	
	//充值和购买红包的返回问题，第二个参数是用于处理
	public static boolean isClosePayDetail = false;
	public static boolean isClosePacketList = false;
	public static boolean isOrderPay = false;
	public static boolean isDetails = false;
	public static boolean isRedpakeDetail = false;
	//当前是否正在付款
	public static boolean isPaying = false;
	
	
	//推送定时器
	Timer timer;
	//yes:已加载notice，从而可以直接返回
	public boolean isLaunchedNotification;
	//是否显示了notice ，true：显示了notice
	public boolean isPushLunch;
	//推送变量
	public boolean isPushSevenColor;
	public boolean isPushLottery;
	public boolean isPushThree;
	public boolean isPushFive;



	/*
	 * 娉ㄦ剰锛氫负浜嗙粰鐢ㄦ埛鎻愪緵鏇村畨鍏ㄧ殑鏈嶅姟锛孉ndroid SDK鑷獀2.1.3鐗堟湰寮�閲囩敤浜嗗叏鏂扮殑Key楠岃瘉浣撶郴銆�
	 * 鍥犳锛屽綋鎮ㄩ�鎷╀娇鐢╲2.1.3鍙婁箣鍚庣増鏈殑SDK鏃讹紝闇�鍒版柊鐨凨ey鐢宠椤甸潰杩涜鍏ㄦ柊Key鐨勭敵璇凤紝 鐢宠鍙婇厤缃祦绋嬭鍙傝�寮�彂鎸囧崡鐨勫搴旂珷鑺�
	 */

	@Override
	public void onCreate() {
		super.onCreate();

		mLocClient = new LocationClient(this);
		setLocationOption();
		mApp = this;
		myLocationListenner = new MyLocationListenner();
		mLocClient.registerLocationListener(myLocationListenner);
		mLocClient.start();
		imageLoader.init(ImageLoaderConfiguration.createDefault(this));
		mInstance = this;
		XkCache.initCacheManager(this);
//		initEngineManager(this);
//		startPushService();
//		startPushServiceForSelf();
		isPushSevenColor = true;
		isPushLottery = true;
		isPushThree = true;
		isPushFive = true;

	}

	private void setLocationOption() {
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(false); // 鎵撳紑gps
		option.setCoorType("bd0911"); // 璁剧疆鍧愭爣绫诲瀷
		option.setAddrType("all"); // 璁剧疆鍦板潃淇℃伅锛屼粎璁剧疆涓衡�all鈥濇椂鏈夊湴鍧�俊鎭紝榛樿鏃犲湴鍧�俊鎭�
		option.setScanSpan(10000); // 璁剧疆瀹氫綅妯″紡锛屽皬浜�绉掑垯涓�瀹氫綅;澶т簬绛変簬1绉掑垯瀹氭椂瀹氫綅
		mLocClient.setLocOption(option);
	}

	public void initEngineManager(Context context) {
		if (mBMapManager == null) {
			mBMapManager = new BMapManager(context);
		}

		if (!mBMapManager.init(strKey, new MyGeneralListener())) {
			Toast.makeText(MyApplication.getInstance().getApplicationContext(),
					"BMapManager  鍒濆鍖栭敊璇�", Toast.LENGTH_LONG).show();
		}
	}

	public static MyApplication getInstance() {
		if (null == mInstance) {
			mInstance = new MyApplication();
		}
		return mInstance;
	}

	// 甯哥敤浜嬩欢鐩戝惉锛岀敤鏉ュ鐞嗛�甯哥殑缃戠粶閿欒锛屾巿鏉冮獙璇侀敊璇瓑
	public static class MyGeneralListener implements MKGeneralListener {

		@Override
		public void onGetNetworkState(int iError) {
			if (iError == MKEvent.ERROR_NETWORK_CONNECT) {
				Toast.makeText(
						MyApplication.getInstance().getApplicationContext(),
						"鎮ㄧ殑缃戠粶鍑洪敊鍟︼紒", Toast.LENGTH_LONG).show();
			} else if (iError == MKEvent.ERROR_NETWORK_DATA) {
				Toast.makeText(
						MyApplication.getInstance().getApplicationContext(),
						"杈撳叆姝ｇ‘鐨勬绱㈡潯浠讹紒", Toast.LENGTH_LONG).show();
			}
		}

		@Override
		public void onGetPermissionState(int iError) {
			if (iError == MKEvent.ERROR_PERMISSION_DENIED) {
				// 鎺堟潈Key閿欒锛�
				// Toast.makeText(MyApplication.getInstance().getApplicationContext(),
				// "璇峰湪 DemoApplication.java鏂囦欢杈撳叆姝ｇ‘鐨勬巿鏉僈ey锛�,
				// Toast.LENGTH_LONG).show();
				// m_bKeyRight = false;
			}
		}
	}

	public class MyLocationListenner implements BDLocationListener {
		@Override
		public void onReceiveLocation(BDLocation location) {
			// Log.i("ShopFragment", location.getAddrStr());
			if (location == null || location.getAddrStr() == null
					|| location.getAddrStr().equals("")) {
				
				return;
			}

			// //閴翠簬鐧惧害鍦板浘璇樊500绫冲乏鍙筹紝杩涜瀹氫綅
			IConstants.lat = location.getLatitude() > 0.0 ? location
					.getLatitude() + IConstants.latCheck : location
					.getLatitude();
			IConstants.lon = location.getLongitude() > 0.0 ? location
					.getLongitude() + IConstants.lonCheck : location
					.getLongitude();

			// IConstants.lat = location.getLatitude();
			// IConstants.lon = location.getLongitude();

			IConstants.currentPosition = "你的当前位置：" + location.getAddrStr();

			if (location.getCity() == null) {
				return;
			} 

		}

		public void onReceivePoi(BDLocation poiLocation) {
			if (poiLocation == null) {
				return;
			}

		}
	}

	public static Application getApplication() {
		return mApp;
	}

	private void startPushService() {
		Intent pushservice = new Intent("com.xkdx.guangguang.service.push");
		startService(pushservice);
	}

	private void startPushServiceForSelf() {
		Intent pushservice = new Intent(
				"com.xkdx.guangguang.service.pushforself");

		startService(pushservice);
	}

	

	public void startMyNotice(){
		if(isLaunchedNotification){
			return;
		}else{
			isLaunchedNotification = true;
		}
		if(isPushSevenColor || isPushLottery || isPushThree || isPushFive){
			SimpleDateFormat   formatter   =   new   SimpleDateFormat   ("yyyy-MM-dd HH:mm:ss");     
			Date   curDate   =   new   Date(System.currentTimeMillis());//获取当前时间     
			int day = getWeekAndDay();
			int timeWhen = 0;//多长时间后提示用户 
			int timeWhenShadow = 0;//用于备份timeWhen
			int KNINE = 21 * 60 * 60; int KDAY = 24 * 60 * 60;
			int curSec = curDate.getHours() * 60 * 60 + (curDate.getMinutes()) * 60 + curDate.getSeconds();
			if(isPushSevenColor){
				if(2 == day || 5 == day || 7 == day){
					if(curDate.getHours() < 21){
						timeWhen = KNINE - curSec;
					}else{
						timeWhen = KNINE + KDAY * 2 - curSec;
						if(2 == day){
							//周2到周5要多一天，就加一天
							timeWhen = KNINE + KDAY * 3 - curSec;
						}
					}
				}else if(1 == day || 4 == day || 6 == day){
					timeWhen = KNINE + KDAY - curDate.getHours() * 60 * 60 - (curDate.getMinutes()) * 60 - curDate.getSeconds();
				}else if(3 == day){
					timeWhen =  KNINE + KDAY * 2 - curSec;
				}
				timeWhenShadow = timeWhen;
			}
			if(isPushLottery){
				if(1 == day || 3 == day || 6 == day){
					if(curDate.getHours() < 21){
						timeWhen = 21 * 60 * 60 - curSec;
					}else{
						timeWhen = KNINE + KDAY * 2 - curSec;
						if(3 == day){
							timeWhen = KNINE + KDAY * 3 - curSec;
						}
					}
				}else if(7 == day || 2 == day || 5 == day){
					timeWhen = KNINE + KDAY - curSec;
				}else if(4 == day){
					timeWhen = KNINE + KDAY * 2 - curSec;
				}
				timeWhenShadow = timeWhen < timeWhenShadow? timeWhen : timeWhenShadow;
			}else if(isPushThree){
				if(curDate.getHours() < 21){
					timeWhen = KNINE - curSec;
				}else{
					timeWhen = KNINE + KDAY - curSec;
				}
				timeWhenShadow = timeWhen < timeWhenShadow? timeWhen : timeWhenShadow;
			}else if(isPushFive){
				if(curDate.getHours() < 21){
					timeWhen = KNINE - curSec;
				}else{
					timeWhen = KNINE + KDAY - curSec;
				}
				timeWhenShadow = timeWhen < timeWhenShadow? timeWhen : timeWhenShadow;
			}
			timer = new Timer(true);
			timer.schedule(new RemindTask(), timeWhenShadow * 1000);//10000);
		}
	}
	
	
	 private int getWeekAndDay(){  
         Calendar calendar= Calendar.getInstance();  
        //获取当前时间为本月的第几周  
         int week = calendar.get(Calendar.WEEK_OF_MONTH);  
         //获取当前时间为本周的第几天  
         int day = calendar.get(Calendar.DAY_OF_WEEK);  
         if (day==1) {  
            day=7;  
            week=week-1;  
         } else {  
            day=day-1;  
         }  
         System.out.println("今天是本月的第" + week + "周"+",星期"+(day));  
         return day;
    } 
	 
	/**
	 * 鐢ㄦ潵鍒ゆ柇鏈嶅姟鏄惁杩愯.
	 * 
	 * @param context
	 * @param className
	 *            鍒ゆ柇鐨勬湇鍔″悕瀛 
	 * @return true 鍦ㄨ繍琛 false 涓嶅湪杩愯
	 */
	public static boolean isServiceRunning(Context mContext, String className) {
		boolean isRunning = false;
		ActivityManager activityManager = (ActivityManager) mContext
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningServiceInfo> serviceList = activityManager
				.getRunningServices(Integer.MAX_VALUE);
		if (!(serviceList.size() > 0)) {
			return false;
		}
		for (int i = 0; i < serviceList.size(); i++) {
			Toast.makeText(mContext, serviceList.get(i).service.getClassName(),
					0).show();

			if (serviceList.get(i).service.getClassName().equals(className)) {
				isRunning = true;
				break;
			}
		}
		return isRunning;
	}
	
	class RemindTask extends TimerTask{   
		 public void run() {
		   notice(); 
		 }  
	};
	void notice(){
		isPushLunch = true;
		NotificationManager nm=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

   		String title = "彩票开奖啦" ;
   		String content = "您定制的彩票信息已开奖，快去查看哦" ;
   	
   		Notification notification = new Notification(R.drawable.xk_lg_caipiao,"通知领取彩票",System.currentTimeMillis());
   		Intent intent = new Intent(this, MainTabActivity.class);
   		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);
   		intent.putExtra("notification", "yes");
   		
   		PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);

   		notification.setLatestEventInfo(this, title, content, pi);
   		nm.notify(1111, notification);
	}
}